import es
import popuplib2

__all__ = ["buildItemPopup"]

def buildItemPopup():
    """
    This function will build the item popup and then return the instance created
    by the popuplib2 function.
    
    @return popuplib2.PageMenu The popup instance                       
    """
    from wcs.libs.items import items
    
    groups = set()
    
    popup = popuplib2.PagedMenu()
    popup.menuselect = _itemGroupCallback
    popup.title = "WarCraft Source: Shop"
    for item in items:
        if item.group not in groups:
            groups.add(item.group)
            popup.add(item.group, "> %s" % item.group)
    return popup

def _itemGroupCallback(args):
    """
    This is executed when an item group is chosen from the list of groups. 
    Build a paged menu listing all the items within that group.
    
    @param dict args A dictionary container containing information passed by
                     popuplib2
    @return popuplib2.PageMenu The popup instance
    """
    from wcs.libs.items import items
    from wcs.libs.common import convertIntToCash
    
    popup = popuplib2.PagedMenu()
    popup.menuselect = _itemCallback
    popup.title = "WarCraft Source: Shop > %s" % args["choice"]
    for item in items:
        if item.group == args["choice"]:
            cost = convertIntToCash(item.cost, symbol="$", splitter=",")
            format = "%s (%s)" % (item.name, cost)
            popup.add(item, format)
    return popup

def _itemCallback(args):
    """
    Executed when an item has been selected from the shop menu. Ensure that we
    build a popup which lists all information about that item and display it to
    the user. This will also contain an option to allow the player to buy the
    item if they have enough cash.
    
    @param dict args A dictionary container containing information passed by
                     popuplib2
    @return popuplib2.Popup The popup instance    
    """
    from wcs.libs.players import players
    from wcs.libs.common import convertIntToCash
    
    item = args["choice"]
    userid = args["userid"]
    player = players[userid]
    cost = convertIntToCash(item.cost, symbol="$", splitter=",")
    cash = convertIntToCash(player.getCash(), symbol="$", splitter=",")
    selectableString = "->" if item.cost <= player.getCash() else ""
    popup = popuplib2.Popup()
    popup.append("WarCraft Source: Shop > %s" % item.name)
    popup.append("-" * 25)
    popup.append(item.description)
    popup.append(" ")
    popup.append("Item Type: %s" % item.group)
    popup.append("Maximum Amount: %s" % item.maxCount)
    popup.append(" ")
    popup.append("Current Cash: %s" % cash)
    popup.append("%s1. Buy (%s)" % (selectableString, cost))
    popup.append("-" * 25)
    popup.append("0. Back")
    popup.menuselect = _buyItem
    popup.menuselect_args["item"] = item 
    popup.menuselect_args["group_popup"] = args["popup"]
    popup.enable_keys = "01"
    return popup

def _buyItem(args):
    """
    This function is executed automatically by popuplib2 when the user selects
    buy item on a particular item. Ensure that we do the checks then return
    the result to the player.
    
    @param dict args A dictionary containing all the arguments automatically
                     passed by popuplib2.
    """
    from wcs.libs.players import players
    from wcs.libs.events import Event
    from wcs.libs.messages import messages
    
    if args["choice"] == 0 or args["choice"] == 10:
        return args["group_popup"]
    userid = args["userid"]
    player = players[userid]
    item = args["item"]
    cash = player.getCash()
    if cash >= item.cost:
        count = player.getItem(item.name).count
        if item.maxCount and count >= item.maxCount:
            messages.send(userid, "too many of that item")
            return args["popup"]
        if item.aliveToUse and es.getplayerprop(userid, 
                                                'CBasePlayer.pl.deadflag'):
            messages.send(userid, "alive to buy item")
            return args["popup"]
        cash -= item.cost
        player.setCash(cash)
        if item.appendToUser is True:
            player.addItem(item.name)
        tokens = {}
        tokens["item"] = item.name
        messages.send(userid, "shopmenu buy item", tokens)
        event = Event("wcs_item_bought")
        event["userid"] = userid
        event["item"] = item.name
        event["cost"] = item.cost
        event.fire()
    else:
        tokens = {}
        tokens["item"] = item.name
        messages.send(userid, "shopmenu low cash", tokens)
    return args["popup"]